<template>
  <div class="anonymous-visits-management">
    <h1>匿名访问记录管理</h1>

    <el-card class="filter-card">
      <el-form :inline="true" :model="filters" class="filter-form">
        <el-form-item label="开始日期">
          <el-date-picker v-model="filters.startDate" type="date" placeholder="选择开始日期" value-format="YYYY-MM-DD" />
        </el-form-item>

        <el-form-item label="结束日期">
          <el-date-picker v-model="filters.endDate" type="date" placeholder="选择结束日期" value-format="YYYY-MM-DD" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="loadVisits">筛选</el-button>
          <el-button @click="resetFilters">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="actions-card">
      <el-button type="danger" @click="showDeleteModal = true" :disabled="selectedVisits.length === 0">
        删除选中记录 ({{ selectedVisits.length }})
      </el-button>
      <el-button type="danger" @click="showDeleteOlderModal = true">
        删除旧记录
      </el-button>
    </el-card>

    <el-card class="table-card">
      <el-table :data="visits" style="width: 100%" v-loading="loading" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="fingerprint" label="访客指纹" width="150" />
        <el-table-column prop="page_url" label="访问页面" />
        <el-table-column prop="visit_time" label="访问时间" width="200">
          <template #default="scope">
            {{ formatDate(scope.row.visit_time) }}
          </template>
        </el-table-column>
      </el-table>

      <el-pagination :current-page="currentPage" :page-size="pageSize" :total="totalVisits"
        layout="total, prev, pager, next, jumper" @current-change="handlePageChange" @size-change="handleSizeChange"
        class="pagination" />
    </el-card>

    <!-- Delete Selected Visits Dialog -->
    <el-dialog v-model="showDeleteModal" title="确认删除" width="30%">
      <span>确定要删除选中的 {{ selectedVisits.length }} 条访问记录吗？此操作不可撤销。</span>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showDeleteModal = false">取消</el-button>
          <el-button type="danger" @click="confirmDeleteSelected">确认删除</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- Delete Older Visits Dialog -->
    <el-dialog v-model="showDeleteOlderModal" title="删除旧记录" width="30%">
      <span>请选择要删除早于指定日期的访问记录：</span>
      <el-date-picker v-model="deleteOlderDate" type="date" placeholder="选择日期" value-format="YYYY-MM-DD"
        style="width: 100%; margin-top: 10px" />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showDeleteOlderModal = false; deleteOlderDate = ''">取消</el-button>
          <el-button type="danger" @click="confirmDeleteOlder" :disabled="!deleteOlderDate">
            确认删除
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {
  ElCard,
  ElForm,
  ElFormItem,
  ElDatePicker,
  ElButton,
  ElTable,
  ElTableColumn,
  ElPagination,
  ElDialog,
  ElMessage,
  ElMessageBox
} from 'element-plus';
import http from '../utils/http';

export default {
  name: 'AnonymousVisits',
  components: {
    ElCard,
    ElForm,
    ElFormItem,
    ElDatePicker,
    ElButton,
    ElTable,
    ElTableColumn,
    ElPagination,
    ElDialog
  },
  data() {
    return {
      visits: [],
      selectedVisits: [],
      loading: false,
      currentPage: 1,
      pageSize: 50,
      totalVisits: 0,
      filters: {
        startDate: '',
        endDate: ''
      },
      showDeleteModal: false,
      showDeleteOlderModal: false,
      deleteOlderDate: ''
    };
  },
  mounted() {
    this.loadVisits();
  },
  methods: {
    async loadVisits() {
      this.loading = true;
      try {
        const response = await http.get('/visits', {
          params: {
            limit: this.pageSize,
            offset: (this.currentPage - 1) * this.pageSize,
            startDate: this.filters.startDate,
            endDate: this.filters.endDate
          }
        });

        if (response.success) {
          this.visits = response.data;
          this.totalVisits = response.total; // Use the total from backend
        } else {
          ElMessage.error('加载访问记录失败: ' + response.message);
        }
      } catch (error) {
        console.error('Error loading visits:', error);
        ElMessage.error('加载访问记录时发生错误');
      } finally {
        this.loading = false;
      }
    },

    handleSelectionChange(selection) {
      this.selectedVisits = selection.map(item => item.id);
    },

    formatDate(dateString) {
      const options = {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      };
      return new Date(dateString).toLocaleDateString('zh-CN', options);
    },

    resetFilters() {
      this.filters = {
        startDate: '',
        endDate: ''
      };
      this.currentPage = 1;
      this.loadVisits();
    },

    handlePageChange(page) {
      this.currentPage = page;
      this.loadVisits();
    },

    handleSizeChange(size) {
      this.pageSize = size;
      this.currentPage = 1;
      this.loadVisits();
    },

    async confirmDeleteSelected() {
      try {
        const response = await http.delete('/visits', {
          data: {
            ids: this.selectedVisits
          }
        });

        if (response.success) {
          this.showDeleteModal = false;
          this.selectedVisits = [];
          this.loadVisits();
          ElMessage.success(`成功删除 ${response.deletedCount} 条记录`);
        } else {
          console.error('Failed to delete visits:', response.message);
          ElMessage.error('删除失败: ' + response.message);
        }
      } catch (error) {
        console.error('Error deleting visits:', error);
        ElMessage.error('删除过程中发生错误');
      }
    },

    async confirmDeleteOlder() {
      try {
        const response = await http.delete('/visits', {
          data: {
            olderThan: this.deleteOlderDate
          }
        });

        if (response.success) {
          this.showDeleteOlderModal = false;
          this.deleteOlderDate = '';
          this.loadVisits();
          ElMessage.success(`成功删除 ${response.deletedCount} 条记录`);
        } else {
          console.error('Failed to delete old visits:', response.data.message);
          ElMessage.error('删除失败: ' + response.message);
        }
      } catch (error) {
        console.error('Error deleting old visits:', error);
        ElMessage.error('删除过程中发生错误');
      }
    }
  }
};
</script>

<style scoped lang="scss">
.anonymous-visits-management {
  padding: 0 20px;
  max-width: 1200px;
  margin: 0 auto;

  h1 {
    margin-top: 0;
  }
}

.filter-card {
  margin-bottom: 20px;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
  align-items: end;
  gap: 15px;
}

.actions-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>